package com.atguigu.srb.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.results.ResultCodeEnum;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.mapper.LendMapper;
import com.atguigu.srb.core.pojo.query.LendQuery;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.*;
import com.atguigu.srb.core.util.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 标的准备表 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2022-10-24
 */
@Service
@Slf4j
public class LendServiceImpl extends ServiceImpl<LendMapper, Lend> implements LendService {
    @Autowired
    private BorrowerService borrowerService;
    @Autowired
    DictService dictService;
    @Autowired
    LendReturnService lendReturnService;
    @Autowired
    UserAccountService userAccountService;
    @Autowired
    LendItemService lendItemService;
    @Autowired
    LendItemReturnService lendItemReturnService;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    TransFlowService transFlowService;
    @Override
    public void createLend(BorrowInfoApprovalVO vo, BorrowInfo borrowInfo) {
        //创建标的对象
        Lend lend = new Lend();
        //BorrowInfo
        lend.setAmount(borrowInfo.getAmount());
        lend.setBorrowInfoId(borrowInfo.getId());
        lend.setUserId(borrowInfo.getUserId());
        lend.setPeriod(borrowInfo.getPeriod());
        lend.setReturnMethod(borrowInfo.getReturnMethod());
        //BorrowInfoApprovalVO
        lend.setLendInfo(vo.getLendInfo());
        lend.setLendYearRate(vo.getLendYearRate().divide(new BigDecimal("100")));
        lend.setTitle(vo.getTitle());
        lend.setServiceRate(vo.getServiceRate().divide(new BigDecimal("100")));
        //放款时间: 放款给借款人的日期  计算借款人利息的日期
        lend.setPaymentTime(null);
        //起息日：  投资人开始投资的日期： 投资人计算利息的日期
        lend.setLendStartDate(vo.getLendStartDate());
        //结息日：  投资人本次投资结算利息的日期
        //使用起息日+借款人借款的时长
        //vo.getLendStartDate()+borrowInfo.getPeriod()
        lend.setLendEndDate(new DateTime(vo.getLendStartDate())
                .plusMonths(borrowInfo.getPeriod()).toDate());
        //审核用户id: 当前审批的管理员id(srb-admin前端使用的是假登录)
        lend.setCheckAdminId(1L);
        //审核时间: 当前时间
        lend.setCheckTime(new Date());
        //平台预期收益:  年化率/12 * 还款的期数* 贷款额度             年化率/12为每月的利率
        BigDecimal exceptAmount = borrowInfo.getAmount()
                .multiply(new BigDecimal(borrowInfo.getPeriod()))
                .multiply(lend.getLendYearRate())
                .divide(new BigDecimal("12"));
        lend.setExpectAmount(exceptAmount);

        //已投金额:默认0
        lend.setInvestAmount(new BigDecimal("0"));
        //投资人数： 默认0
        lend.setInvestNum(0);
        //状态:
        /*
        CHECK(0, "待发布"),
        INVEST_RUN(1, "募资中"),
        PAY_RUN(2, "还款中"),
        PAY_OK(3, "已结清"),
        FINISH(4, "结标"),
        CANCEL(-1, "已撤标"),
         */
        lend.setStatus(1);
        //实际收益
        lend.setRealAmount(new BigDecimal("0"));
        //发布日期
        lend.setPublishDate(new Date());

        lend.setPaymentAdminId(null);
        //最低投资金额
        lend.setLowestAmount(new BigDecimal("0"));
        //标的编号:后端生成的
        lend.setLendNo(LendNoUtils.getLendNo());

        //保存到数据库
        this.save(lend);
    }

    @Override
    public List<Lend> listLends() {

        List<Lend> lends = this.list(new LambdaQueryWrapper<Lend>()
                .orderByDesc(Lend::getPublishDate));
        /*
        CHECK(0, "待发布"),
        INVEST_RUN(1, "募资中"),
        PAY_RUN(2, "还款中"),
        PAY_OK(3, "已结清"),
        FINISH(4, "结标"),
        CANCEL(-1, "已撤标"),
         */
        //状态转为字符串
        lends.forEach(lend->{
            getLendStatus(lend);
        });
        return lends;
    }

    @Override
    public Map<String, Object> lendDetail(String id) {
        //id代表lend的id
        //1、根据id查询标的信息
        Lend lend = this.getById(id);
        getLendStatus(lend);//修改状态字符串
        lend.setReturnMethodMsg(dictService.queryDictNameByDictCodeAndValue("returnMethod",lend.getReturnMethod()));
        //2、根据标的的user_id 去borrower表中查询借款人数据
        Long userId = lend.getUserId(); //用户id
        Borrower borrower = borrowerService.getOne(new LambdaQueryWrapper<Borrower>()
                .eq(Borrower::getUserId, userId)
                .orderByDesc(Borrower::getCreateTime)
                .last("limit 1"));
        //将borrower转为BorrowerDetailVO对象方便前端展示
        BorrowerDetailVO borrowerDetailVO = borrowerService.selectBorrowerDetail(borrower.getId().toString());

        Map<String,Object> map = new HashMap<>();
        map.put("lend",lend);
        map.put("borrower",borrowerDetailVO);
        return map;
    }

    private void getLendStatus(Lend lend) {
        Integer status = lend.getStatus();
        switch (status) {
            case 0:
                lend.setLendStatus("待发布");
                break;
            case 1:
                lend.setLendStatus("募资中");
                break;
            case 2:
                lend.setLendStatus("还款中");
                break;
            case 3:
                lend.setLendStatus("已结清");
                break;
            case 4:
                lend.setLendStatus("结标");
                break;
            case -1:
                lend.setLendStatus("已撤标");
                break;
        }
    }
    /*
    SELECT COUNT(*) FROM lend WHERE is_deleted = 0
    AND (
        (title LIKE ? OR title LIKE ?)
        AND (lend_year_rate >= ? AND lend_year_rate < ? OR lend_year_rate >= ? AND lend_year_rate < ?)
        AND (period >= ? AND period < ? OR period >= ? AND period < ?)
        AND (return_method = ?)
    )
     */
    @Override
    public Page<Lend> listLendsPage(LendQuery lendQuery, Integer pageNum, Integer pageSize) {
        Page<Lend> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Lend> queryWrapper = new LambdaQueryWrapper<>();
        List<Integer> lendTitles = lendQuery.getLendTitles();
        List<Integer> lendYearRates = lendQuery.getLendYearRates();
        List<Integer> periods = lendQuery.getPeriods();
        List<Integer> returnMethods = lendQuery.getReturnMethods();
        //标的类型  车易贷= 0   装修贷= 1     房易贷= 2     债权贷=3    白领贷=4
        if(!CollectionUtils.isEmpty(lendTitles)){
            queryWrapper.and(w->{
                //遍历lendTitles 将提交的每个标的类型 转为 字符串集合
                lendTitles.forEach(lendTitle -> {
                    switch (lendTitle) {
                        case 0:
                            w.or().likeRight(Lend::getTitle ,"车易贷" );
                            break;
                        case 1:
                            w.or().likeRight(Lend::getTitle ,"装修贷" );
                            break;
                        case 2:
                            w.or().likeRight(Lend::getTitle ,"房易贷" );
                            break;
                        case 3:
                            w.or().likeRight(Lend::getTitle ,"债权贷" );
                            break;
                        case 4:
                            w.or().likeRight(Lend::getTitle ,"白领贷" );
                            break;
                        default:
                            w.or().likeRight(Lend::getTitle ,"其他" );
                            break;
                    }
                    //使用titles设置条件模糊查询
//                queryWrapper.or().likeRight(Lend::getTitle ,title );
                });

            });

        }
        // ( or or ) and ( )
        //年利率： 0： 12以下，1：12~14  ，2 14~16  ,3 16以上
        if(!CollectionUtils.isEmpty(lendYearRates)){
            queryWrapper.and(w ->{
                lendYearRates.forEach(lendYearRate->{
                    switch(lendYearRate){
                        case 0:
                            w.or().lt(Lend::getLendYearRate , 0.12);
                            break;
                        case 1:
                            w.or().ge(Lend::getLendYearRate , 0.12).lt(Lend::getLendYearRate , 0.14);
                            break;
                        case 2:
                            w.or().ge(Lend::getLendYearRate , 0.14)
                                    .lt(Lend::getLendYearRate , 0.16);
                            break;
                        default:
                            w.or().ge(Lend::getLendYearRate , 0.16);
                            break;
                    }
                });
            });

        }
        //还款期限： 0:1月以下  1:1~3   2：3~6   3：6~12   4:12
        if(!CollectionUtils.isEmpty(periods)){
            queryWrapper.and(w ->{
                periods.forEach(period->{
                    switch(period){
                        case 0:
                            w.or().lt(Lend::getPeriod , 1);
                            break;
                        case 1:
                            w.or().ge(Lend::getPeriod , 1).lt(Lend::getPeriod , 3);
                            break;
                        case 2:
                            w.or().ge(Lend::getPeriod , 3).lt(Lend::getPeriod , 6);
                            break;
                        case 3:
                            w.or().ge(Lend::getPeriod , 6).lt(Lend::getPeriod , 12);
                            break;
                        default:
                            w.or().ge(Lend::getPeriod , 12);
                            break;
                    }
                });
            });

        }
        //还款方式
        // 0:  到期还本付息   1：按月付息,到期还本
        //2 等额本息  3 等额本金
        if(!CollectionUtils.isEmpty(returnMethods)){
            queryWrapper.and(w ->{
                returnMethods.forEach(returnMethod->{
                    switch(returnMethod){
                        case 0:
                            w.or().eq(Lend::getReturnMethod , 4);
                            break;
                        case 1:
                            w.or().eq(Lend::getReturnMethod , 3);
                            break;
                        case 2:
                            w.or().eq(Lend::getReturnMethod , 1);
                            break;
                        case 3:
                            w.or().eq(Lend::getReturnMethod , 2);
                            break;
                    }
                });
            });

        }


        this.page(page,queryWrapper);
        page.getRecords().forEach(lend -> {
            getLendStatus(lend);
            String returnMethod = dictService.queryDictNameByDictCodeAndValue("returnMethod", lend.getReturnMethod());
            lend.setReturnMethodMsg(returnMethod);
        });
        return page;
    }
    //放款业务：
    @Override
    public void makeLoan(String id) {
        //0、访问hfb放款接口完成转账等一系列操作
        Lend lend = this.getById(id);
        //不是生成自动提交的表单字符串，而是采用了发送http网络请求同步等待返回的结果
        Map<String, Object> params = new HashMap<>();
        params.put("agentId",HfbConst.AGENT_ID);
        //之前投标时使用的项目编号
        params.put("agentProjectCode",lend.getLendNo());
        //生成当前订单唯一的编号
        params.put("agentBillNo",LendNoUtils.getLoanNo());
        /*
            计算手续费：平台的收益
                标的投标总金额*期数*月服务费率
         */
        BigDecimal amount = lend.getInvestAmount();
        Integer period = lend.getPeriod();
        //平台服务费率
        //参数1：除数    参数2：小数点后的精度   参数3：四舍五入的模式
        //divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
        BigDecimal monthRate = lend.getServiceRate().divide(new BigDecimal("12"), 8,
                RoundingMode.DOWN);//小数点8位以后的数据直接丢弃
        params.put("mchFee",amount.multiply(new BigDecimal(period)).multiply(monthRate));
        params.put("note","放款");
        params.put("timestamp",System.currentTimeMillis());
        params.put("sign",RequestHelper.getSign(params));

        //参数1：请求参数，参数2：hfb放款地址
        JSONObject jsonObject = RequestHelper.sendRequest(params, HfbConst.MAKE_LOAD_URL);
        log.info("放款结果："+jsonObject.toJSONString());
        //{"agentProjectCode":"LEND20221111103704299","voteAmt":"195.0000080000","hyFee":"0","mchFee":"4.9999920000",
        // "resultCode":"0000","resultMsg":"放款成功","agentBillNo":"LOAN20221111114624851"}
        if(!"0000".equals(jsonObject.get("resultCode"))){
            //放款失败
            log.error("放款失败,{}" , jsonObject.toJSONString());
            throw new BusinessException(ResultCodeEnum.MAKE_LOAN_ERROR);
        }
        //标的的编号
        String agentProjectCode = jsonObject.get("agentProjectCode").toString();
        String voteAmt = jsonObject.get("voteAmt").toString();
        String mchFee = jsonObject.get("mchFee").toString();
        //上面访问hfb放款接口时生成的唯一编号：可以防止hfb响应结果被篡改(如果agentBillNo等于上面发送请求时的生成的编号)
        String agentBillNo = jsonObject.get("agentBillNo").toString();
        String hyFee = jsonObject.get("hyFee").toString();
        //1、修改标的的状态(放款管理员数据、状态、放款时间)
        lend = this.getOne(new LambdaQueryWrapper<Lend>()
                .eq(Lend::getLendNo, agentProjectCode));
        /*
            CHECK(0, "待发布"),
            INVEST_RUN(1, "募资中"),
            PAY_RUN(2, "还款中"),
            PAY_OK(3, "已结清"),
            FINISH(4, "结标"),
            CANCEL(-1, "已撤标"),
        */
        lend.setStatus(2);
        lend.setPaymentTime(new Date());//放款时间
        lend.setPaymentAdminId(1L); //放款管理员id
        this.updateById(lend);
        //????
        //2、将放款的金额转给借款人: 放款成功时hfb已经完成了向hfb借款人用户转账的操作
        //如果借款人在本地没有账户数据，新建账户并转入放款金额
        //如果借款人账户存在，更新账户的金额
        Long userId = lend.getUserId();//获取标的的借款人id
        //获取借款人账户对象
        UserAccount borrowUserAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
                .eq(UserAccount::getUserId, userId) //用户id
                .eq(UserAccount::getStatus, 1) //状态可用
                .last("limit 1"));
        if(borrowUserAccount==null){
            borrowUserAccount = new UserAccount();
            borrowUserAccount.setFreezeAmount(new BigDecimal("0"));
            borrowUserAccount.setAmount(new BigDecimal(voteAmt));
            borrowUserAccount.setStatus(1);
            borrowUserAccount.setUserId(userId);
            borrowUserAccount.setChargeNo(LendNoUtils.getChargeNo());
            userAccountService.save(borrowUserAccount);
        }else{
            borrowUserAccount.setAmount(borrowUserAccount.getAmount()
                    .add(new BigDecimal(voteAmt)));
            userAccountService.updateById(borrowUserAccount);
        }
        //保存借款人账户入账的日志：
        UserInfo borrowUserInfo = userInfoService.getById(borrowUserAccount.getUserId());
        TransFlow transFlow = new TransFlow();
        transFlow.setUserId(borrowUserAccount.getUserId());
        transFlow.setUserName(borrowUserInfo.getName());
        //交易类型（1：充值 2：提现 3：投标 4：投资回款  5、放款.）
        transFlow.setTransType(5);
        transFlow.setTransTypeName("放款");
        transFlow.setTransNo(LendNoUtils.getNo());
        transFlow.setTransAmount(new BigDecimal(voteAmt));
        transFlow.setMemo(JSON.toJSONString(borrowUserAccount));
        transFlowService.save(transFlow);
        //3、修改投资人的冻结金额 扣除放款金额(一个标的有多个投资人)
        /*
            3.1 查询本标的所有的投资成功的记录(lend_item)
            3.2 遍历所有的投资记录(lend_item)
                根据lend_item中的投资人id 去他的账户中将冻结金额扣减 投资记录中投资的金额
         */
        List<LendItem> lendItems = lendItemService.list(new LambdaQueryWrapper<LendItem>()
                .eq(LendItem::getLendId, lend.getId())
                .eq(LendItem::getStatus, 1));
        //扣除投资人账户的投资成功的余额:voteAmt代表所有投资人投资的总和
        lendItems.forEach(lendItem -> {
            //查询投资人一个可用的账户
            UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
                    .eq(UserAccount::getUserId, lendItem.getInvestUserId())
                    .eq(UserAccount::getStatus, 1)
                    .last("limit 1"));
            //扣除当前投资人 本次投资的金额
            userAccount.setFreezeAmount(userAccount.getFreezeAmount()
                    .subtract(lendItem.getInvestAmount()));
            userAccountService.updateById(userAccount);

            UserInfo userInfo = userInfoService.getById(userAccount.getUserId());
            TransFlow transFlow2 = new TransFlow();
            transFlow2.setUserId(userAccount.getUserId());
            transFlow2.setUserName(userInfo.getName());
            //交易类型（1：充值 2：提现 3：投标 4：投资回款  5、放款  6、账户投资扣减.）
            transFlow2.setTransType(6);
            transFlow2.setTransTypeName("账户投资扣减");
            transFlow2.setTransNo(LendNoUtils.getNo());
            transFlow2.setTransAmount(lendItem.getInvestAmount());
            transFlow2.setMemo(JSON.toJSONString(userAccount));
            transFlowService.save(transFlow2);
        });
        //4、保存资金往来日志

        //5、放款成功：
        //5.1 生成还款计划：借款人一期要还多少钱    lend_return  一个标的按照借款人借款期数 每一期生成一个还款计划
        //一个标的的所有钱都放款给了一个借款人，还款计划就是该借款人的还款计划
        List<LendReturn> lendReturns = new ArrayList<>();
        //        period 还款期数
        for (Integer i = 1; i <= period; i++) {
            //从1开始生成 第N期的还款计划存到lend_return
            LendReturn lendReturn = new LendReturn();
            lendReturn.setLendId(lend.getId());
            lendReturn.setBorrowInfoId(lend.getBorrowInfoId());
            //还款编号
            lendReturn.setReturnNo(LendNoUtils.getReturnNo());
            lendReturn.setUserId(lend.getUserId());

            lendReturn.setAmount(lend.getInvestAmount());
            lendReturn.setBaseAmount(lend.getInvestAmount());
            //当前的期数
            lendReturn.setCurrentPeriod(i);
            lendReturn.setLendYearRate(lend.getLendYearRate());
            lendReturn.setReturnMethod(lend.getReturnMethod());
            // 投资记录生成回款计划时，使用一个标的每一期多个投资的 本金、利息、总额 累加后再设置
//            lendReturn.setPrincipal();
//            lendReturn.setInterest();
//            lendReturn.setTotal();
            lendReturn.setFee(new BigDecimal(0));
            //当前期的还款日期
            lendReturn.setReturnDate(new DateTime(lend.getLendStartDate())
                    .plusMonths(i).toDate());//第N期应该在设置的计息起始日开始+N个月
            if(i==period){
                //是否为最后一期还款
                lendReturn.setLast(true);
            }else{
                lendReturn.setLast(false);

            }
            lendReturn.setStatus(0);
            lendReturns.add(lendReturn);
        }
        lendReturnService.saveBatch(lendReturns);

        //5.2 生成回款计划：投资人一期收回多少钱
        // lend_item_return 一个标的 每个投资人 投资的金额 按照借款人借款期数  每一期生成一个回款计划
        //1、查询本标的所有的lendItems:为每一个lendItem生成对应的回款计划(period:回款期数)
        Integer returnMethod = lend.getReturnMethod();
        //存储 所有的lendItem生成的 回款计划对象
        List<LendItemReturn> allLendItemReturns = new ArrayList<>();
        lendItems.forEach(lendItem -> {
            //遍历生成lendItem的N期的回款计划
            List<LendItemReturn> lendItemReturns = new ArrayList<>();
            //获取lendItem每一期应还款的本金和利息的map
            Map<Integer, BigDecimal> perMonthPrincipal = new HashMap<>();
            Map<Integer, BigDecimal> perMonthInterest = new HashMap<>();
            switch(returnMethod){
                case 1:
                    perMonthPrincipal =
                            Amount1Helper.getPerMonthPrincipal(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);
                    perMonthInterest =
                            Amount1Helper.getPerMonthInterest(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);
                    break;
                case 2:
                    perMonthPrincipal =
                            Amount2Helper.getPerMonthPrincipal(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);
                    perMonthInterest =
                            Amount2Helper.getPerMonthInterest(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);

                    break;
                case 3:
                    perMonthPrincipal =
                            Amount3Helper.getPerMonthPrincipal(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);
                    perMonthInterest =
                            Amount3Helper.getPerMonthInterest(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);

                    break;
                case 4:
                    perMonthPrincipal =
                            Amount4Helper.getPerMonthPrincipal(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);
                    perMonthInterest =
                            Amount4Helper.getPerMonthInterest(lendItem.getInvestAmount(), lendItem.getLendYearRate(), period);

                    break;
            }


            for (Integer i = 1; i <= period; i++) {
                LendItemReturn lendItemReturn = new LendItemReturn();
                //回款是基于用户的还款来保存的： 回款计划需要绑定 本期还款计划的id
                lendItemReturn.setLendReturnId(lendReturns.get(i-1).getId());
                lendItemReturn.setLendItemId(lendItem.getId());
                lendItemReturn.setLendId(lendItem.getLendId());
                lendItemReturn.setInvestUserId(lendItem.getInvestUserId());
                lendItemReturn.setInvestAmount(lendItem.getInvestAmount());
                lendItemReturn.setCurrentPeriod(i);
                lendItemReturn.setLendYearRate(lendItem.getLendYearRate());
                lendItemReturn.setReturnMethod(returnMethod);
                //每期回款的本金：根据还款方式计算每期回款的金额
                /*
                    1、判断使用哪种方式获取本金利息
                    2、使用期数去获取本期的本金和利息
                 */
                //每期回款的利息：根据还款方式计算每期回款的利息
                //如果returnMethod=4，每一期还款本金为0，利息也为0
                if(returnMethod==4){
                    lendItemReturn.setPrincipal(new BigDecimal("0"));
                    lendItemReturn.setInterest(new BigDecimal("0"));
                    if(i==period){
                        lendItemReturn.setPrincipal(perMonthPrincipal.get(1));
                        lendItemReturn.setInterest(perMonthInterest.get(1));
                    }
                }else{
                    lendItemReturn.setPrincipal(perMonthPrincipal.get(i));
                    lendItemReturn.setInterest(perMonthInterest.get(i));
                }
                lendItemReturn.setTotal(lendItemReturn.getPrincipal()
                        .add(lendItemReturn.getInterest()));
                lendItemReturn.setFee(new BigDecimal("0"));
                //本期还款计划日期
                lendItemReturn.setReturnDate(new DateTime(lendItem.getLendStartDate())
                        .plusMonths(i).toDate());
                lendItemReturn.setStatus(0);
                lendItemReturns.add(lendItemReturn);
            }
            lendItemReturnService.saveBatch(lendItemReturns);
            //保存正在遍历的lendItem生成的回款计划集合
            allLendItemReturns.addAll(lendItemReturns);
        });


        //5.3 还款计划：每期还款的本金 利息 和本息 还未设置
        //查询lend的每一个lendItem的 每一期的本金累加设置给对应期数的 还款计划对象 更新
        for (int i = 1; i <= lendReturns.size(); i++) {
            int a = i;
            //挑出本期还款计划 的所有的 回款计划对象
            List<LendItemReturn> collect = allLendItemReturns.stream().filter(lendItemReturn ->
                    lendItemReturn.getCurrentPeriod() == a).collect(Collectors.toList());
            BigDecimal principal = collect.stream().map(lendItemReturn -> lendItemReturn.getPrincipal())
                    .reduce((m, v) -> m.add(v)).get();
            BigDecimal interest = collect.stream().map(lendItemReturn -> lendItemReturn.getInterest())
                    .reduce((m, v) -> m.add(v)).get();
            BigDecimal total = collect.stream().map(lendItemReturn -> lendItemReturn.getTotal())
                    .reduce((m, v) -> m.add(v)).get();
            lendReturns.get(i-1).setPrincipal(principal);
            lendReturns.get(i-1).setInterest(interest);
            lendReturns.get(i-1).setTotal(total);
        }
        lendReturnService.updateBatchById(lendReturns);
    }
}
